package com.sfac.modules.common.serviceimpl;

import com.sfac.config.ResourceConfigBean;
import com.sfac.modules.common.vo.Result;
import com.sfac.modules.common.vo.StatusCode;
import com.sfac.modules.common.service.ImageService;
import com.sfac.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Author:唐琳的爹
 * @BelongsProject:hqyj_springboot
 * @BelongsPackage:com.sfac.modules.common.vo.serviceimpl
 * @CreateTime:2022/8/23 10:26:27
 */
@Service
@Slf4j
public class ImageServiceImpl implements ImageService {

    @Autowired
    private ResourceConfigBean resourceConfigBean;
    // 获取当前项目的artifactId
    @Value("${project.artifactId}")
    private String artifactId;

    @Override
    public Result<String> upLoadImage(MultipartFile file, String imageTypeName) {
        // 判断图片是否为空
        if (file.isEmpty()){
            return new Result<>(StatusCode.ERR,"文件为空");
        }
        // 对图片进行校验
        if (!FileUtil.isImage(file)){
            return new Result<>(StatusCode.ERR,"请选择图片");
        }

        // 图片名称
        String imageName = String.format("%s.%s",System.currentTimeMillis()
                                        ,FileUtil.getFileType(file.getOriginalFilename()));

        // 构建目标文件夹，如果不存在则创建
        String destFolder = String.format("%s%s/%s",
                System.getProperty("os.name").toLowerCase().startsWith("win")?
                        resourceConfigBean.getLocalPathForWin():
                        resourceConfigBean.getLocalPathForLin(),
                artifactId,imageTypeName);
        File destFolderFile = new File(destFolder);
        if (!destFolderFile.exists()){
            // 创建目标文件夹
            destFolderFile.mkdirs();
        }

        // 构造图片存放的绝对路径(通过System.getProperty("os.name")方法获取当前操作系统的类型)
        String destPath = String.format("%s/%s",
               destFolder,imageName);

        // 构造图片相对路径
        String relativePath = String.format("%s%s/%s/%s",
                resourceConfigBean.getResourcePath(),artifactId,imageTypeName,imageName);

        // 保存图片
        try {
            file.transferTo(new File(destPath));
        } catch (IOException e) {
            e.printStackTrace();
            // 记录日志用于查看
            log.info(e.getMessage());
            return new Result<>(StatusCode.ERR,"更换头像失败");
        }
        // 成功
        return new Result<>(StatusCode.SUCCESS,"更换头像成功",relativePath);
    }
}
